package com.shchuangzhi.smartguard.core.command;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import com.shchuangzhi.smartguard.SharedPref;
import com.shchuangzhi.smartguard.core.Clock;
import com.shchuangzhi.smartguard.core.Machine;
import com.shchuangzhi.smartguard.core.Util;

import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * Created by j_hu on 5/7/17.
 */

public class SyncProfileCommand extends Command implements Command.CommandHandler {
    public SyncProfileCommand() {
        super("profile.sync");
    }

    @Override
    protected OutputStream fill(OutputStream output) {
        return output;
    }

    @Override
    protected CommandHandler getHandler(String commandName) {
        return this;
    }

    @Override
    protected String getType() {
        return null;
    }

    @Override
    protected String getURL() {
        String url = SharedPref.getInstance().getRemoteServiceURL();
        if (url != null) {
            url = String.format("%s/smartguard/v1/api/sync/profile?id=%s",
                    url.replaceAll("/$",""),
                    Machine.getInstance().getRootName());
        }
        return url;
    }

    @Override
    public boolean handle(InputStream input) {
        boolean handleOk = false;
        try {
            Gson gson = new Gson();
            SyncProfileCommandRS rs = (SyncProfileCommandRS)gson.fromJson(
                    Util.readAll(input),
                    new TypeToken<SyncProfileCommandRS>(){}.getType());

            if (rs != null) {
                try {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Clock.sync(format.parse(rs.getTime()));
                }catch(ParseException e) {
                    raiseError(e);
                }

                if (rs.getHost() != null && rs.getHost().length() != 0) {
                    Machine.getInstance().setHostIp(rs.getHost());
                }
                handleOk = true;
            }
        }catch (Exception e) {
            this.raiseError(e);
        }
        return handleOk;
    }

    public class SyncProfileCommandRS {
        private String time;
        @SerializedName("local_host")
        private String host;

        public String getTime() {
            return time;
        }
        public String getHost() {
            return host;
        }
    }
}
